package com.hbnu.ojcodesandbox.utils;

import cn.hutool.core.util.StrUtil;
import com.hbnu.ojcodesandbox.model.ExecuteMessage;
import org.springframework.util.StopWatch;

import javax.swing.text.SimpleAttributeSet;
import java.io.*;

/**
 * @Description: 进程工具类
 * @Author: Hu Bowen
 */
public class ProcessUtils {


    /**
     * 执行进程并获取信息
     *
     * @param runProcess
     * @param opName
     */
    public static ExecuteMessage runProcessAndGetMessage(Process runProcess, String opName) {

        ExecuteMessage executeMessage = new ExecuteMessage();

        try {
            // 使用计时器工具, 记录程序的执行时间
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();


            int exitValue = runProcess.waitFor();
            if (exitValue == 0) {
                System.out.println(opName + "编译成功");
                // 分批获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                StringBuilder compileOutputStringBuilder = new StringBuilder();
                // 逐行读取
                String compileOutputLine;
                while ((compileOutputLine = bufferedReader.readLine()) != null) {
                    compileOutputStringBuilder.append(compileOutputLine).append("\n");
                }
                executeMessage.setMessage(compileOutputStringBuilder.toString());

            } else {
                // 异常退出
                System.out.println(opName + "编译失败,错误码" + exitValue);

                // 分批获取进程的正常输出
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
                StringBuilder compileOutputStringBuilder = new StringBuilder();
                // 逐行读取
                String compileOutputLine;
                while ((compileOutputLine = bufferedReader.readLine()) != null) {
                    compileOutputStringBuilder.append(compileOutputLine);
                }

                // 分批获取进程的输出
                BufferedReader errorBufferedReader =
                        new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
                StringBuilder errorCompileOutputStringBuilder = new StringBuilder();
                // 逐行读取
                String errorCompileOutputLine;
                while ((errorCompileOutputLine = errorBufferedReader.readLine()) != null) {
                    errorCompileOutputStringBuilder.append(errorCompileOutputLine).append("\n");
                }

                executeMessage.setErrorMessage(errorCompileOutputStringBuilder.toString());


                // 停止计时 ,记录最后结束的记录时间
                stopWatch.stop();
                executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return executeMessage;
    }


    /**
     * 执行交互式进程并获取信息
     *
     * @param
     * @param
     */
    public static ExecuteMessage runInteractProcessAndGetMessage(Process runProcess,
                                                                 String opName, String args) {

        ExecuteMessage executeMessage = new ExecuteMessage();

        try {


            // 向控制台输入程序
            OutputStream outputStream = runProcess.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            String[] s = args.split(" ");

            String join = StrUtil.join("n", s) + "\n";
            outputStreamWriter.write(join); // 执行输入 1 2
            outputStreamWriter.flush(); // 执行回车命令, 执行输入的发送

            // 分批获取进程的正常输出
            InputStream inputStream = runProcess.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder compileOutputStringBuilder = new StringBuilder();
            // 逐行读取
            String compileOutputLine;
            while ((compileOutputLine = bufferedReader.readLine()) != null) {
                compileOutputStringBuilder.append(compileOutputLine).append("\n");
            }
            executeMessage.setMessage(compileOutputStringBuilder.toString());

            // 资源回收和释放, 否则导致卡死
            outputStream.close();
            outputStreamWriter.close();
            inputStream.close();
            runProcess.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return executeMessage;
    }


}
